package com.cangshi.utils;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.entity.JsonInfo;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * Created by Eoly on 2017/6/16.
 */
public class HttpUtils {
    private HttpUtils() {
    }

    public static void outPrint(ServletResponse response, JSONObject jsonObject) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");//设置编码
            response.setContentType("application/json");//设置返回类型
            out = response.getWriter();
            out.println(jsonObject);//输出
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }

    public static boolean isAjaxRequestInternal(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static void sendJsonResultByCheckAjax(
            JsonInfo jsonInfo,
            ServletRequest request,
            ServletResponse response

    ) {
        if (HttpUtils.isAjaxRequestInternal(request)) {
            outPrint(response, jsonInfo);
        }
    }
}
